package com.jacen.fzxs.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jacen.fzxs.entity.ImageEntity;
import com.jacen.fzxs.entity.WallEntity;
import com.jacen.fzxs.service.IImageService;
import com.jacen.fzxs.service.IWallService;
import com.jacen.fzxs.util.Constants;
import com.jacen.fzxs.util.EntityUtils;
import com.jacen.fzxs.util.ServletUtils;
import com.jacen.fzxs.util.Utils;

/**
 * 图片Controller
 * @author Jacen
 *
 */
@Controller
public class ImageController extends BaseController {

	@Resource
	private IImageService imageService;

	@Resource
	private IWallService wallService;

	/**
	 * 获取图片列表
	 * @param request
	 * @param curPage
	 * @param modelMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/image/list.do")
	public String getList(HttpServletRequest request, Integer curPage, ModelMap modelMap) throws Exception {
		if (curPage == null){
			curPage = 1;
		}
		Map<String, String> params = ServletUtils.getParameterMap(request);
		List<Map<String, Object>> list = imageService.getPage(curPage, Constants.PAGE_SIZE, params);
		long totalRecords = imageService.getCount(params);
		long totalPage = totalRecords / Constants.PAGE_SIZE + (totalRecords % Constants.PAGE_SIZE != 0 ? 1 : 0);

		modelMap.put("list", list);
		modelMap.addAttribute("curPage", curPage);
		modelMap.addAttribute("totalRecords", totalRecords);
		modelMap.addAttribute("totalPage", totalPage);
		modelMap.addAttribute("pagesize", Constants.PAGE_SIZE);
		return "image/list";
	}

	@RequestMapping("/image/init.do")
	@ResponseBody
	public String init(HttpServletRequest request) throws Exception {
		List<WallEntity> list = wallService.getAll();
		String imageStr = "";
		String[] imageUrls;
		ImageEntity imageEntity = null;
		for (WallEntity entity : list) {
			if (entity.getImages() == null || "".equals(entity.getImages()))
				continue;
			imageStr = entity.getImages();
			imageUrls = imageStr.split(",");
			for (int i = 0; i < imageUrls.length; i++) {
				imageEntity = new ImageEntity();
				imageEntity.setId(EntityUtils.createId32());
				imageEntity.setName(imageUrls[i].substring(imageUrls[i].lastIndexOf("/") + 1));
				imageEntity.setWid(entity.getId());
				imageEntity.setUrl(imageUrls[i]);
				imageService.insert(imageEntity);
			}
			entity.setImages("");
			wallService.update(entity);
		}
		return Utils.normalJsonResp();
	}

	@RequestMapping("/image/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request, String id) {
		imageService.deleteById(id);
		return Utils.normalJsonResp();
	}

	public static void main(String[] args) {
	}

}
